/* Andreas Baum
 * Code inspired by the JBonjourBrowser, by Denis Abramov, Myounghwan Lee (Columbia)
 * jbpClientConnector.java
 * Registers the DAAP service
 * CS 78 - Networks
 */

/* 
 * The notion of "server" in this project can lead to confusion: 
 * Indeed, it is employed with two separate meanings.
 * 1. The central login server
 * 2. The "server" side of the iTunes connection to which another proxy connect
 * , and which allows another user to access the user's iTunes library.
 */


package jbpClientConnector;

import com.apple.dnssd.DNSSD;
import com.apple.dnssd.DNSSDException;
import com.apple.dnssd.DNSSDRegistration;
import com.apple.dnssd.DNSSDService;
import com.apple.dnssd.RegisterListener;
import com.apple.dnssd.TXTRecord;

public class ServiceRegistrar implements RegisterListener
{
	private static String name;
	private static String service;
	private boolean successful;
	private DNSSDRegistration reg;
	
	public ServiceRegistrar (String userName, String serviceName, int port)
	throws DNSSDException, InterruptedException
	{
		service = serviceName;
		name = userName;
		successful = false;
		
		TXTRecord txtRecord = new TXTRecord(  );
		txtRecord.set("txtvers", "1");
		txtRecord.set("status", "ready");
		txtRecord.set("difficulty", "medium");

		reg = DNSSD.register(0, DNSSD.ALL_INTERFACES,
				name, service, null,  			// Name, type, and domain
				null, port,                   	// Target host and port
				txtRecord, this);             	// TXT record and listener object

	}

	/** Method inherited from RegisterListener: failure */
	public void operationFailed(DNSSDService service, int errorCode)
	{
		System.err.println("Registration failed " + errorCode);
	}

	/** Method inherited from RegisterListener: success */
	public void serviceRegistered(DNSSDRegistration registration, int flags,
			String serviceName, String regType, String domain)
	{
		System.out.println("Registered Name  : " + serviceName);
		/*System.out.println("           Type  : " + regType);
		System.out.println("           Domain: " + domain);*/
		successful = true;
	}
	
	/** Returns true if registration was successful */
	public boolean isRegistered(){
		return successful;
	}
	
	/** Stops the registration */
	public void killRegistration(){
		System.out.println("Stopping registration.");
		reg.stop();
	}
}
